import {login, logout} from 'src/api/admin'
import {getToken, setToken, removeToken, setUserInfo, getUserInfo, removeUserInfo} from 'src/utils/auth'

const state = {
  token: getToken(),
  userInfo: getUserInfo(),
  editPassword: false
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_USER_INFO(state, userInfo) {
    state.userInfo = userInfo
  },
  SET_EDIT_PASSWORD(state, data) {
    state.editPassword = data
  }
};

const actions = {
  // user login
  login({commit}, userInfo) {
    console.log(userInfo);
    const {login_name, password} = userInfo;
    return new Promise((resolve, reject) => {
      login({login_name: login_name.trim(), password: password}).then(response => {

        const {data} = response;

        // console.log(data);
        commit('SET_TOKEN', data.token);
        setToken(data.token);
        setUserInfo(data);
        commit('SET_USER_INFO', data)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },


  // user logout
  logout({commit, state}) {
    return new Promise((resolve, reject) => {

      commit('SET_TOKEN', '');
      removeToken();
      removeUserInfo();
      //可以清除菜单
      commit('leftMenu/SET_LEFT_MENU', [], {root: true});
      resolve();
      // logout(state.token).then(() => {
      //   commit('SET_TOKEN', '')
      //   removeToken();
      //   removeUserInfo();
      //   //可以清除菜单
      //   commit('leftMenu/SET_LEFT_MENU', [], {root: true});
      //   resolve()
      // }).catch(error => {
      //   reject(error)
      // })
    })
  },

  // remove token
  resetToken({commit}) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      removeToken();
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

